import React, { useEffect, useState } from 'react'
import {
  Button,
  Form,
  Input,
  Table,
  Popconfirm,
  Modal,
  message,
  InputNumber,
  Select,
  DatePicker
} from 'antd'
// import { getUser, addUser, editUser, deleteUser } from '../../api'
import { useApi } from '../../api'
import dayjs from 'dayjs'

function User() {
  //请求接口
  const { getUser, addUser, editUser, deleteUser } = useApi()

  const [listData, setListData] = useState(null)
  const [tableData, setTableData] = useState()
  // 0新增，1编辑
  const [modalType, setModalType] = useState(0)
  const [isModalOpen, setIsModalOpen] = useState(false)
  //创建form实例
  const [form] = Form.useForm()
  const [messageApi, contextHolder] = message.useMessage()

  // 新增
  const handleClick = (type, rowData) => {
    setIsModalOpen(!isModalOpen)
    if (type === 'add') {
      setModalType(0)
    } else {
      setModalType(1)
      const cloneData = JSON.parse(JSON.stringify(rowData))
      cloneData.birth = dayjs(cloneData.birth)
      // 表单数据回填
      form.setFieldsValue(cloneData)
    }
  }

  //提交，搜索
  const handleSearch = e => {
    setListData({
      name: e.keyWord
    })
  }
  useEffect(() => {
    getTableData()
  }, [listData])

  //删除
  const handleDelete = async rowData => {
    try {
      let res = await deleteUser({ id: rowData.id })
      getTableData()
    } catch (error) {
      message.error('异常')
      console.log('err', error)
    }
  }

  // 获取列表信息
  const getTableData = () => {
    getUser(listData).then(data => {
      setTableData(data.list)
    })
  }

  // 弹窗确定
  const handleOk = () => {
    //表单校验
    form.validateFields().then(
      async val => {
        try {
          val.birth = dayjs(val.birth).format('YYYY-MM-DD')

          //编辑
          if (modalType) {
            let res = await editUser(val)
            handleCancel()
            getTableData()
            messageApi.open({
              type: 'success',
              content: '编辑成功',
              duration: 1
            })
          } else {
            let res = await addUser(val)
            handleCancel()
            getTableData()
            messageApi.open({
              type: 'success',
              content: '添加成功',
              duration: 1
            })
          }
        } catch (error) {
          message.error('异常')
          console.log('err', error)
        }
      },
      () => {
        messageApi.open({
          type: 'error',
          content: '异常',
          duration: 1
        })
      }
    )
  }
  // 弹窗取消
  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields()
  }

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '年龄',
      dataIndex: 'age'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render: val => {
        return val ? '女' : '男'
      }
    },
    {
      title: '出生日期',
      dataIndex: 'birth'
    },
    {
      title: '地址',
      dataIndex: 'addr'
    },
    {
      title: '操作',
      render: rowData => {
        return (
          <div className="flex">
            {contextHolder}
            <Button className="mr-[0.0625rem]" onClick={() => handleClick('edit', rowData)}>
              编辑
            </Button>
            <Popconfirm
              type="提示"
              description="此操作将删除该用户，是否继续"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(rowData)}
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        )
      }
    }
  ]

  useEffect(() => {
    ;(async () => {
      try {
        let res = await getUser(listData)
        setTableData(res.list)
      } catch (error) {
        message.error('异常')
        console.log('err', error)
      }
    })()
  }, [])

  return (
    <div>
      <div className="flex justify-between">
        <Button type="primary" onClick={() => handleClick('add')}>
          +新增
        </Button>
        <Form layout="inline" onFinish={handleSearch}>
          <Form.Item name="keyWord">
            <Input></Input>
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit" type="primary">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table className="mt-0.5" columns={columns} dataSource={tableData} rowKey={'id'}></Table>
      <Modal
        open={isModalOpen}
        title={modalType ? '编辑用户' : '新增用户'}
        onCancel={handleCancel}
        cancelText="取消"
        onOk={handleOk}
        okText="确定"
      >
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
          {modalType == 1 && (
            <Form.Item name="id" hidden>
              <Input></Input>
            </Form.Item>
          )}
          <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
            <Input placeholder="请输入姓名"></Input>
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[
              { required: true, message: '请输入年龄' },
              { type: 'number', message: '年龄必须是数字' }
            ]}
          >
            <InputNumber placeholder="请输入年龄"></InputNumber>
          </Form.Item>
          <Form.Item label="性别" name="sex" rules={[{ required: true, message: '请选择性别' }]}>
            <Select
              options={[
                { value: 0, label: '男' },
                { value: 1, label: '女' }
              ]}
            ></Select>
          </Form.Item>
          <Form.Item
            label="出生日期"
            name="birth"
            rules={[{ required: true, message: '请选择出生日期' }]}
          >
            <DatePicker placeholder="请选择" format="YYYY/MM/DD"></DatePicker>
          </Form.Item>
          <Form.Item label="地址" name="addr" rules={[{ required: true, message: '请输入地址' }]}>
            <Input placeholder="请输入地址"></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default User
